package com.example.husbandry_online.view;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;


import com.example.husbandry_online.MainActivity;
import com.example.husbandry_online.R;
import com.example.husbandry_online.model.User;
import com.example.husbandry_online.retrofit.ResponseModel;
import com.example.husbandry_online.retrofit.ServiceGetter;
import com.example.husbandry_online.service.UserService;
import com.tencent.mmkv.MMKV;


import java.util.regex.Matcher;
import java.util.regex.Pattern;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LoginFragment extends Fragment {
    View root;
    Button register;
    Button loginPhone;
    Button forgetPwd;
    Button LoginNormal;
    TextView telephoneOrid;
    TextView password;
    String telephoneOridnum;
    String Password;
    MMKV kv;
    Bundle bundle = new Bundle();//声明一个Bundle对象
    CheckBox rememberPassword;
    public void init(){
        telephoneOrid = getActivity().findViewById(R.id.telephoneOrid);
        password = getActivity().findViewById(R.id.password);
        telephoneOridnum = telephoneOrid.getText().toString();
        Password = password.getText().toString();
        rememberPassword = getActivity().findViewById(R.id.rememberPassword);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        //设置MMKV根目录，以及初始化
        String rootDir = MMKV.initialize(getContext());
        Log.v("MMKVActivity","mmkv root: " + rootDir);
        kv = MMKV.defaultMMKV();


        if(root == null) {
            root = inflater.inflate(R.layout.fragment_login, container, false);
        }
        return root;
    }
    //分别是进入 注册页面 手机验证码登录页面  忘记密码页面  的按钮点击事件注册
    public void inRegisterPage(){
        //进入注册页面
        register = getActivity().findViewById(R.id.Register);
        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeRegisterFrag(new RegisterFragment());
            }
        });
    }
    public void inLoginByPhoneCodePage(){
        loginPhone = getActivity().findViewById(R.id.LoginPhone);
        loginPhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //1表示手机验证码
                bundle.putInt("show",1);   //用Bundle对象携带需要传递的信息
                Fragment registerPhone =  new RegisterPhoneFragment();
                registerPhone.setArguments(bundle);
                changeRegisterFrag(registerPhone);
            }
        });
    }
    public void inForgetPwdPage(){
        forgetPwd = getActivity().findViewById(R.id.forgetPwd);
        forgetPwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //0表示忘记密码
                bundle.putInt("show",0);   //用Bundle对象携带需要传递的信息
                Fragment registerPhone =  new RegisterPhoneFragment();
                registerPhone.setArguments(bundle);
                changeRegisterFrag(registerPhone);
            }
        });
    }

    //登录 按钮 点击事件注册
    public void loginButtonOnclick(){
        LoginNormal = getActivity().findViewById(R.id.LoginNormal);
        LoginNormal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //分别得到 手机号/身份证号 和 密码
                telephoneOrid = getActivity().findViewById(R.id.telephoneOrid);
                telephoneOridnum = telephoneOrid.getText().toString();
                password = getActivity().findViewById(R.id.password);
                Password = password.getText().toString();

                if(telephoneOridnum.equals("")){
                    Toast.makeText(getContext(), "电话号码不能为空,请重新输入", Toast.LENGTH_LONG).show();
                }else {
                    //利用正则表达式，判断是电话号码还是身份证号
                    boolean phoneNumberValid = isPhone(telephoneOridnum);//isMobileNO(telephoneOridnum);
                    boolean isId = personIdValidation(telephoneOridnum);

                    //定义网络请求
                    UserService userService = ServiceGetter.getService(UserService.class);

                    if (phoneNumberValid == true){
                        //是有效的电话号码
                        userService.login(new User("0","0",telephoneOridnum,Password,"0","0",1)).enqueue(new Callback<ResponseModel<User>>() {
                            @Override
                            public void onResponse(Call<ResponseModel<User>> call, Response<ResponseModel<User>> response) {
                                String result = response.body().getResult();
                                //Toast.makeText(getContext(),"result:"+result,Toast.LENGTH_LONG).show();
                                if (!result.equals("")){
                                    if(result.equals("SUCCESS")){
                                        Toast.makeText(getContext(),"登录成功",Toast.LENGTH_LONG).show();
                                        isRememberUserAndPassword();
                                    }else {
                                        //Toast.makeText(getContext(),"登录失败",Toast.LENGTH_SHORT).show();
                                        Toast.makeText(getContext(),"错误："+response.body().getMessage(),Toast.LENGTH_LONG).show();
                                    }
                                }else {
                                    Toast.makeText(getContext(),"网络繁忙，请重新尝试",Toast.LENGTH_LONG).show();
                                }

                            }

                            @Override
                            public void onFailure(Call<ResponseModel<User>> call, Throwable t) {
                                Toast.makeText(getContext(),"网络繁忙，请重新尝试",Toast.LENGTH_LONG).show();
                                t.printStackTrace();
                            }
                        });
                    }else if(isId == true){
                        //是有效的身份证号
                        userService.login(new User("0","0",telephoneOridnum,Password,"0","0",2)).enqueue(new Callback<ResponseModel<User>>() {
                            @Override
                            public void onResponse(Call<ResponseModel<User>> call, Response<ResponseModel<User>> response) {
                                String result = response.body().getResult();
                                //Toast.makeText(getContext(),"result:"+result,Toast.LENGTH_LONG).show();
                                if (!result.equals("")){
                                    if(result.equals("SUCCESS")){
                                        Toast.makeText(getContext(),"登录成功",Toast.LENGTH_LONG).show();
                                        isRememberUserAndPassword();
                                    }else {
                                        Toast.makeText(getContext(),"登录失败",Toast.LENGTH_SHORT).show();
                                        Toast.makeText(getContext(),"错误："+response.body().getMessage(),Toast.LENGTH_LONG).show();
                                    }
                                }else {
                                    Toast.makeText(getContext(),"网络繁忙，请重新尝试",Toast.LENGTH_LONG).show();
                                }
                            }

                            @Override
                            public void onFailure(Call<ResponseModel<User>> call, Throwable t) {
                                Toast.makeText(getContext(),"网络繁忙，请重新尝试",Toast.LENGTH_LONG).show();

                                t.printStackTrace();
                            }
                        });
                    }else {
                        Toast.makeText(getContext(), "输入账号格式有误，请重新输入", Toast.LENGTH_LONG).show();
                    }
                }


            }
        });
    }
    //是否记住密码
    public void isRememberUserAndPassword(){
        if (rememberPassword.isChecked()){
            kv.encode("isRememberUserAndPassword","true");
            //保存账号密码
            kv.encode("telephoneOrId",telephoneOrid.getText().toString());
            kv.encode("password",password.getText().toString());


        }else {
            //Toast.makeText(getContext(), "这是取消按钮", Toast.LENGTH_SHORT).show();
            //点击不记住按钮，使用mmkv存入不记住
            kv.encode("isRememberUserAndPassword","false");
        }
        Intent intent=new Intent(getContext(), MainActivity.class);
        startActivity(intent);
}
    void loadLastSetUserAndPwd(){
        Log.v("ljh","进入了loadLast");
        //显示上次保存的密码
        //如果上次记住了密码 则直接默认输上密码
        Log.v("ljh","last:"+kv.decodeString("isRememberUserAndPassword"));
        if(kv.decodeString("isRememberUserAndPassword") != null){
            if(kv.decodeString("isRememberUserAndPassword").equals("true")){
                telephoneOrid.setText(kv.decodeString("telephoneOrId"));
                telephoneOridnum = telephoneOrid.getText().toString();
                password.setText(kv.decodeString("password"));
                Password = password.getText().toString();
                Log.v("ljh","telephone="+telephoneOridnum);
                Log.v("ljh","pwd="+password);
            }
        }

    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        init();

        //显示上次保存的账号密码
        loadLastSetUserAndPwd();

        //进入注册页面
        inRegisterPage();
        //进入手机验证码登录页面
        inLoginByPhoneCodePage();
        //进入忘记密码页面
        inForgetPwdPage();

        //登录按钮点击事件注册
        loginButtonOnclick();
    }

    //更换Fragment
    public void changeRegisterFrag(Fragment newFragment){
        LoginAndRegisterActivity activity = (LoginAndRegisterActivity) getActivity();
        activity.changeFragment(newFragment);
    }

    //两个正则表达式，分别验证身份证号和手机号
    public boolean personIdValidation(String text) {
        /**
         * 验证身份证号是否符合规则
         * @param text 身份证号
         * @return
         */
        String regx = "[0-9]{17}x";
        String reg1 = "[0-9]{15}";
        String regex = "[0-9]{18}";
        return text.matches(regx) || text.matches(reg1) || text.matches(regex);
    }
    /**
     * 手机号码校验(三大运营商最新号段 合作版 2021-03)
     * 移动号段：
     * 134 135 136 137 138 139 147 148 150 151 152 157 158 159 172 178 182 183 184 187 188 195 198
     * <p>
     * 联通号段：
     * 130 131 132 145 146 155 156 166 167 171 175 176 185 186 196
     * <p>
     * 电信号段：
     * 133 149 153 173 174 177 180 181 189 191 193 199
     * <p>
     * 虚拟运营商:
     * 162 165 167 170 171
     * <p>
     * 13开头排序：(0-9)（134 135 136 137 138 139 130 131 132 133）
     * 14开头排序：(5-9)（147 148 145 146 149）
     * 15开头排序：(0-3|5-9)（150 151 152 157 158 159 155 156 153）
     * 16开头排序：(6-7)（166 167）
     * 17开头排序：(1-8)（172 178 171 175 176 173 174 177）
     * 18开头排序：(0-9)（182 183 184 187 188 185 186 180 181 189）
     * 19开头排序：(1|3|5|6|8|9)（195 198 196 191 193 199）
     *
     * @param phone 手机号码
     * @return 是否属于三大运营商号段范围
     * @see {https://www.qqzeng.com/article/phone.html}
     */
    public static boolean isPhone(String phone) {
        String regex = "^((13[0-9])|(14[5-9])|(15([0-3]|[5-9]))|(16[6-7])|(17[1-8])|(18[0-9])|(19[1|3])|(19[5|6])|(19[8|9]))\\d{8}$";
        Pattern p = Pattern.compile(regex);
        return p.matcher(phone).matches();
    }
}